<template>
    <el-select v-if="type === 'select'"
        v-model="localModelValue"
        :placeholder="placeholder"
        :readonly="readonly"
        :disabled="disabled"
        :clearable="clearable"
        class="w100">
        <el-option 
            v-for="item in dictionarys"
            :key="item.dictValue"
            :label="item.dictName"
            :value="item.dictValue">
        </el-option>
    </el-select>
    <!-- checkbox-->
    <!-- <el-checkbox-group v-model="localModelValue" v-if="type === 'checkbox'">
        <el-checkbox v-for="item in dictionarys" :label="item.dictValue" :value="item.dictValue">{{ item.dictName }}</el-checkbox>
    </el-checkbox-group> -->
    <!-- radio -->
    <el-radio-group v-model="localModelValue" v-if="type === 'radio'">
        <el-radio v-for="item in dictionarys" :label="item.dictValue" :value="item.dictValue">{{ item.dictName }}</el-radio>
    </el-radio-group>
</template>
<script lang="ts">
import { ref, toRefs, reactive, defineComponent, onMounted, onUnmounted, watch, watchEffect } from 'vue';
import { getDictionaryByLabel } from '/@/api/system/dictionary/index';

export default defineComponent({
    name: "dictionary",
    emits: ['update:modelValue'],
    props: {
        modelValue: {
            type: [String, Number, Array],
            default: '',
        },
        dictLabel: {
            type: String,
            default: 'sys_data_status',
        },
        placeholder: {
            type: String,
            default: '请选择枚举类型',
        },
        type: {
            type: String,
            default: 'select',
        },
        readonly: {
            type: Boolean,
            default: false,
        },
        disabled: {
            type: Boolean,
            default: false,
        },
        clearable: {
            type: Boolean,
            default: true,
        }
    },
    setup(props, { emit }) {
        const localModelValue = ref(props.modelValue);
        const state = reactive({
            dictionarys: [],
        });

        const loadDictionarys = () => {
            getDictionaryByLabel({ dictLabel: props.dictLabel }).then((res: any) => {
                if (res.code == 0) {
                    state.dictionarys = res.data;
                }
            });
        };

        // 页面加载时
        onMounted(() => {
            loadDictionarys();
            localModelValue.value = props.modelValue;
        });
        onUnmounted(() => {
            localModelValue.value = null;
        });

        // 监听model数据变化
        watch(() => props.modelValue, (newValue) => {
            localModelValue.value = newValue;
            emit('update:modelValue', localModelValue.value);
        });
        watchEffect(() => {
            if(localModelValue.value != ''){
                emit('update:modelValue', localModelValue.value);
            }
        });

        return {
            localModelValue,
            ...toRefs(state),
        };
    },
});
</script>